<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图书馆管理系统 - 我的借阅</title>
    <link rel="stylesheet" href="styles.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <script src="auth.js"></script>
    <script src="permission-control.js"></script>
</head>
<body>
    <!-- 主系统页面 -->
    <div id="mainPage" class="page active">
        <!-- 顶部导航栏 -->
        <header class="header">
            <div class="header-left">
                <button class="sidebar-toggle" onclick="toggleSidebar()">
                    <i class="fas fa-bars"></i>
                </button>
                <h1 class="logo">
                    <i class="fas fa-book"></i>
                    图书馆管理系统
                </h1>
            </div>
            <div class="header-right">
                <div class="notification-icon" onclick="showNotifications()">
                    <i class="fas fa-bell"></i>
                    <span class="notification-badge" id="notificationBadge">0</span>
                </div>
                <div class="user-menu">
                    <span class="user-name" id="currentUserName">用户</span>
                    <div class="user-dropdown">
                        <button class="dropdown-btn">
                            <i class="fas fa-user-circle"></i>
                            <i class="fas fa-chevron-down"></i>
                        </button>
                        <div class="dropdown-content">
                            <a href="#" onclick="showProfile()">个人资料</a>
                            <a href="#" onclick="changePassword()">修改密码</a>
                            <a href="#" onclick="logout()">退出登录</a>
                        </div>
                    </div>
                </div>
            </div>
        </header>

        <!-- 侧边栏 -->
        <aside class="sidebar" id="sidebar">
            <nav class="sidebar-nav">
                <ul id="sidebarMenu">
                    <!-- 菜单将通过JavaScript动态生成 -->
                </ul>
            </nav>
        </aside>

        <!-- 主内容区域 -->
        <main class="main-content">
            <!-- 我的借阅页面 -->
            <div id="myBorrows" class="content-page active">
                <div class="page-header">
                    <h2>我的借阅</h2>
                    <div class="header-actions">
                        <button class="btn btn-info" onclick="loadMyBorrows()">
                            <i class="fas fa-refresh"></i>
                            刷新
                        </button>
                    </div>
                </div>
                
                <!-- 借阅统计 -->
                <div class="stats">
                    <div class="stat-card">
                        <div class="stat-label">当前借阅</div>
                        <div class="stat-value" id="currentBorrowCount">0</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-label">历史借阅</div>
                        <div class="stat-value" id="totalBorrowCount">0</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-label">逾期记录</div>
                        <div class="stat-value" id="overdueBorrowCount">0</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-label">待付费用</div>
                        <div class="stat-value" id="pendingFees">¥0.00</div>
                    </div>
                </div>

                <div class="page-filters">
                    <div class="filter-group">
                        <input type="text" id="borrowSearch" placeholder="搜索我的借阅记录..." class="form-control">
                        <select id="borrowStatusFilter" class="form-control">
                            <option value="">所有状态</option>
                            <option value="borrowing">借阅中</option>
                            <option value="returned">已归还</option>
                            <option value="overdue">逾期</option>
                            <option value="lost">丢失</option>
                        </select>
                        <button class="btn btn-secondary" onclick="searchMyBorrows()">
                            <i class="fas fa-search"></i>
                            搜索
                        </button>
                    </div>
                </div>
                <div class="table-container">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>图书</th>
                                <th>作者</th>
                                <th>借阅时间</th>
                                <th>应还时间</th>
                                <th>实际归还时间</th>
                                <th>续借次数</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="myBorrowTableBody">
                        </tbody>
                    </table>
                </div>
                <div class="pagination" id="myBorrowPagination">
                </div>
                <div class="pagination-tools" id="myBorrowPaginationTools"></div>
            </div>
        </main>
    </div>

    <!-- 模态框 -->
    <div id="modalOverlay" class="modal-overlay">
        <div class="modal">
            <div class="modal-header">
                <h3 id="modalTitle">标题</h3>
                <button class="modal-close" onclick="closeModal()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="modal-body" id="modalBody">
            </div>
            <div class="modal-footer" id="modalFooter">
            </div>
        </div>
    </div>

    <!-- 加载提示 -->
    <div id="loadingOverlay" class="loading-overlay">
        <div class="loading-spinner">
            <i class="fas fa-spinner fa-spin"></i>
            <p>加载中...</p>
        </div>
    </div>

    <!-- 消息提示 -->
    <div id="messageContainer" class="message-container">
    </div>

    <script src="api.js"></script>
    <script>
        // 全局变量
        let currentUser = null;
        let currentPageNum = 1;
        let currentPageSize = 10;

        // 页面初始化
        document.addEventListener('DOMContentLoaded', function() {
            setTimeout(() => {
                initializeApp();
            }, 100);
        });

        // 初始化应用
        async function initializeApp() {
            try {
                // 使用通用权限检查
                if (!initializePagePermission()) {
                    return;
                }
                
                currentUser = authManager.getCurrentUser();
                
                // 生成动态菜单
                generateSidebarMenu();
                
                // 更新用户信息
                document.getElementById('currentUserName').textContent = currentUser.realName || currentUser.username;
                
                // 加载我的借阅数据
                await loadMyBorrows();
                
                // 加载统计数据
                await loadMyBorrowStats();
                
                // 加载未读通知数量
                await loadUnreadNotificationCount();
            } catch (error) {
                console.error('初始化应用失败:', error);
                Utils.showMessage('初始化应用失败', 'error');
            }
        }

        // 生成侧边栏菜单
        function generateSidebarMenu() {
            const sidebarMenu = document.getElementById('sidebarMenu');
            if (sidebarMenu) {
                sidebarMenu.innerHTML = authManager.generateSidebarMenu();
            }
        }

        // 切换侧边栏
        function toggleSidebar() {
            const sidebar = document.getElementById('sidebar');
            sidebar.classList.toggle('active');
        }

        // 退出登录
        function logout() {
            authManager.logout();
        }

        // 显示通知
        function showNotifications() {
            window.location.href = 'notifications.html';
        }

        // 显示个人资料
        function showProfile() {
            Utils.showMessage('个人资料功能开发中', 'info');
        }

        // 修改密码
        function changePassword() {
            Utils.showMessage('修改密码功能开发中', 'info');
        }

        // 加载未读通知数量
        async function loadUnreadNotificationCount() {
            try {
                const response = await NotificationAPI.countUnreadNotifications(currentUser.userId);
                if (response.result === 'SUCCESS') {
                    const badge = document.getElementById('notificationBadge');
                    if (badge) {
                        badge.textContent = response.data || 0;
                        badge.style.display = response.data > 0 ? 'block' : 'none';
                    }
                }
            } catch (error) {
                console.error('Load unread notification count error:', error);
            }
        }

        // 加载我的借阅数据
        async function loadMyBorrows(page = 1) {
            try {
                Utils.showLoading();
                
                const keyword = document.getElementById('borrowSearch')?.value || '';
                let status = document.getElementById('borrowStatusFilter')?.value || '';
                
                // 将字符串状态转换为后端可识别的枚举码
                if (status) {
                    const map = { borrowing: 1, returned: 2, overdue: 3, lost: 4 };
                    status = map[status] !== undefined ? map[status].toString() : status;
                } else {
                    status = '';
                }
                
                // 只查询当前用户的借阅记录
                const response = await BorrowAPI.pageBorrows(page, currentPageSize, currentUser.userId.toString(), status, keyword);
                
                if (response.result === 'SUCCESS') {
                    renderMyBorrowTable(response.data.records);
                    renderPagination('myBorrowPagination', page, response.data.pages, loadMyBorrows);
                    renderPaginationTools('myBorrowPaginationTools', response.data.pages,
                        (n) => { currentPageNum = n; loadMyBorrows(n); },
                        (size) => { currentPageSize = size; currentPageNum = 1; loadMyBorrows(1); }
                    );
                } else {
                    Utils.showMessage(response.message || '加载借阅数据失败', 'error');
                }
            } catch (error) {
                Utils.showMessage('加载借阅数据失败', 'error');
                console.error('My borrows load error:', error);
            } finally {
                Utils.hideLoading();
            }
        }

        // 加载我的借阅统计
        async function loadMyBorrowStats() {
            try {
                // 获取当前借阅数量
                const currentResponse = await BorrowAPI.pageBorrows(1, 1, currentUser.userId.toString(), '1', '');
                if (currentResponse.result === 'SUCCESS') {
                    document.getElementById('currentBorrowCount').textContent = currentResponse.data.total || 0;
                }
                
                // 获取总借阅数量
                const totalResponse = await BorrowAPI.pageBorrows(1, 1, currentUser.userId.toString(), '', '');
                if (totalResponse.result === 'SUCCESS') {
                    document.getElementById('totalBorrowCount').textContent = totalResponse.data.total || 0;
                }
                
                // 获取逾期数量
                const overdueResponse = await BorrowAPI.pageBorrows(1, 1, currentUser.userId.toString(), '3', '');
                if (overdueResponse.result === 'SUCCESS') {
                    document.getElementById('overdueBorrowCount').textContent = overdueResponse.data.total || 0;
                }
                
                // 获取待付费用
                try {
                    const feeResponse = await FeeAPI.getUserFeeStats(currentUser.userId);
                    if (feeResponse.result === 'SUCCESS') {
                        document.getElementById('pendingFees').textContent = Utils.formatMoney(feeResponse.data.unpaidAmount || 0);
                    }
                } catch (error) {
                    console.error('Load pending fees error:', error);
                }
            } catch (error) {
                console.error('Load my borrow stats error:', error);
            }
        }

        // 渲染我的借阅表格
        function renderMyBorrowTable(borrows) {
            const tbody = document.getElementById('myBorrowTableBody');
            if (!tbody) return;
            
            if (!borrows || borrows.length === 0) {
                tbody.innerHTML = '<tr><td colspan="8" style="text-align: center;">暂无借阅记录</td></tr>';
                return;
            }
            
            try {
                tbody.innerHTML = borrows.map(borrow => `
                    <tr>
                        <td>${borrow.bookName || ''}</td>
                        <td>${borrow.author || ''}</td>
                        <td>${borrow.borrowDate || borrow.borrowTime ? Utils.formatDate(borrow.borrowDate || borrow.borrowTime) : ''}</td>
                        <td>${borrow.dueDate || borrow.dueTime ? Utils.formatDate(borrow.dueDate || borrow.dueTime) : ''}</td>
                        <td>${borrow.returnDate || borrow.returnTime ? Utils.formatDate(borrow.returnDate || borrow.returnTime) : '-'}</td>
                        <td>${borrow.renewCount || 0}</td>
                        <td><span class="status-badge status-${borrow.status || 'borrowing'}">${Utils.getStatusText(borrow.status) || '未知'}</span></td>
                        <td>
                            <div class="btn-group-table">
                                ${borrow.status === 'borrowing' ? `
                                    <button class="btn btn-sm btn-warning" onclick="requestRenew(${borrow.borrowId})">
                                        <i class="fas fa-redo"></i> <span>申请续借</span>
                                    </button>
                                ` : ''}
                                ${borrow.status === 'lost' ? `
                                    <button class="btn btn-sm btn-primary" onclick="viewPaymentInfo(${borrow.borrowId})">
                                        <i class="fas fa-money-bill-wave"></i> <span>查看费用</span>
                                    </button>
                                ` : ''}
                                <button class="btn btn-sm btn-info" onclick="viewBorrowDetail(${borrow.borrowId})">
                                    <i class="fas fa-eye"></i> <span>详情</span>
                                </button>
                            </div>
                        </td>
                    </tr>
                `).join('');
            } catch (error) {
                console.error('渲染借阅表格失败:', error);
                tbody.innerHTML = '<tr><td colspan="8" style="text-align: center;">数据渲染失败</td></tr>';
            }
        }

        // 搜索我的借阅记录
        function searchMyBorrows() {
            currentPageNum = 1;
            loadMyBorrows(1);
        }

        // 申请续借
        async function requestRenew(borrowId) {
            if (!confirm('确定要申请续借吗？')) return;
            
            try {
                Utils.showLoading();
                const response = await BorrowAPI.renewBook(borrowId, 15); // 默认续借15天
                
                if (response.result === 'SUCCESS') {
                    Utils.showMessage('续借申请成功', 'success');
                    loadMyBorrows();
                    loadMyBorrowStats();
                } else {
                    Utils.showMessage(response.message || '续借申请失败', 'error');
                }
            } catch (error) {
                Utils.showMessage('续借申请失败', 'error');
            } finally {
                Utils.hideLoading();
            }
        }

        // 查看费用信息
        async function viewPaymentInfo(borrowId) {
            try {
                Utils.showLoading();
                const response = await BorrowAPI.getFineAmount(borrowId);
                
                if (response.result === 'SUCCESS') {
                    showModal('费用信息', `
                        <div class="payment-info">
                            <div class="detail-row">
                                <label>借阅记录ID:</label>
                                <span>${borrowId}</span>
                            </div>
                            <div class="detail-row">
                                <label>待付金额:</label>
                                <span class="fee-amount">${Utils.formatMoney(response.data)}</span>
                            </div>
                            <div class="detail-row">
                                <label>说明:</label>
                                <span>请联系图书管理员处理费用支付</span>
                            </div>
                        </div>
                    `, `
                        <button class="btn btn-secondary" onclick="closeModal()">关闭</button>
                    `);
                } else {
                    Utils.showMessage(response.message || '获取费用信息失败', 'error');
                }
            } catch (error) {
                Utils.showMessage('获取费用信息失败', 'error');
            } finally {
                Utils.hideLoading();
            }
        }

        // 查看借阅详情
        async function viewBorrowDetail(recordId) {
            try {
                Utils.showLoading();
                const response = await BorrowAPI.getBorrowById(recordId);
                
                if (response.result === 'SUCCESS') {
                    const borrow = response.data;
                    let fineInfo = '';
                    if (borrow.status === 'lost' || borrow.status === 'overdue') {
                        try {
                            const fineResponse = await BorrowAPI.getFineAmount(recordId);
                            if (fineResponse.result === 'SUCCESS') {
                                fineInfo = `
                                <div class="detail-row">
                                    <label>待付金额:</label>
                                    <span>${Utils.formatMoney(fineResponse.data)}</span>
                                </div>`;
                            }
                        } catch (error) {
                            console.error('获取罚款金额失败:', error);
                        }
                    }
                    
                    showModal('借阅详情', `
                        <div class="borrow-detail">
                            <div class="detail-row">
                                <label>借阅ID:</label>
                                <span>${borrow.borrowId}</span>
                            </div>
                            <div class="detail-row">
                                <label>图书:</label>
                                <span>${borrow.bookName} - ${borrow.author}</span>
                            </div>
                            <div class="detail-row">
                                <label>借阅时间:</label>
                                <span>${Utils.formatDate(borrow.borrowDate || borrow.borrowTime)}</span>
                            </div>
                            <div class="detail-row">
                                <label>应还时间:</label>
                                <span>${Utils.formatDate(borrow.dueDate || borrow.dueTime)}</span>
                            </div>
                            <div class="detail-row">
                                <label>实际归还时间:</label>
                                <span>${borrow.returnDate || borrow.returnTime ? Utils.formatDate(borrow.returnDate || borrow.returnTime) : '未归还'}</span>
                            </div>
                            <div class="detail-row">
                                <label>续借次数:</label>
                                <span>${borrow.renewCount || 0}</span>
                            </div>
                            <div class="detail-row">
                                <label>状态:</label>
                                <span class="status-badge status-${borrow.status}">${Utils.getStatusText(borrow.status)}</span>
                            </div>
                            ${fineInfo}
                        </div>
                    `, `
                        <button class="btn btn-secondary" onclick="closeModal()">关闭</button>
                    `);
                } else {
                    Utils.showMessage(response.message || '获取借阅详情失败', 'error');
                }
            } catch (error) {
                Utils.showMessage('获取借阅详情失败', 'error');
            } finally {
                Utils.hideLoading();
            }
        }

        // 显示模态框
        function showModal(title, body, footer) {
            document.getElementById('modalTitle').textContent = title;
            document.getElementById('modalBody').innerHTML = body;
            document.getElementById('modalFooter').innerHTML = footer;
            document.getElementById('modalOverlay').classList.add('active');
        }

        // 关闭模态框
        function closeModal() {
            document.getElementById('modalOverlay').classList.remove('active');
        }

        // 渲染分页组件
        function renderPagination(containerId, currentPage, totalPages, onPageChange) {
            const container = document.getElementById(containerId);
            if (!container) return;
            
            if (totalPages <= 1) {
                container.innerHTML = '';
                return;
            }
            
            container.innerHTML = '';
            container.appendChild(Utils.createPagination(currentPage, totalPages, onPageChange));
        }

        // 渲染分页工具栏
        function renderPaginationTools(containerId, totalPages, onJump, onSizeChange) {
            const c = document.getElementById(containerId);
            if (!c) return;
            c.innerHTML = `
                <span>到第</span>
                <input id="${containerId}-jump" type="number" min="1" max="${totalPages}" value="${currentPageNum}" style="width:60px">
                <span>页</span>
                <button id="${containerId}-go" class="btn btn-sm btn-primary">确定</button>
                <span style="margin-left:12px">每页</span>
                <select id="${containerId}-size" style="width:90px">
                    <option ${currentPageSize==10?'selected':''} value="10">10 条/页</option>
                    <option ${currentPageSize==20?'selected':''} value="20">20 条/页</option>
                    <option ${currentPageSize==50?'selected':''} value="50">50 条/页</option>
                    <option ${currentPageSize==100?'selected':''} value="100">100 条/页</option>
                </select>
            `;
            const goBtn = document.getElementById(`${containerId}-go`);
            const jumpInput = document.getElementById(`${containerId}-jump`);
            const sizeSelect = document.getElementById(`${containerId}-size`);
            if (goBtn && jumpInput) {
                goBtn.onclick = () => {
                    const n = parseInt(jumpInput.value || '1', 10);
                    const page = Math.min(Math.max(1, n), totalPages);
                    onJump(page);
                };
            }
            if (sizeSelect) {
                sizeSelect.onchange = () => {
                    const size = parseInt(sizeSelect.value, 10);
                    onSizeChange(size);
                };
            }
        }
    </script>
</body>
</html>